package cn.itcast.service.impl;

import cn.itcast.dao.CheckGroupDao;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.pojo.CheckGroup;
import cn.itcast.service.CheckGroupService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;
    @Override
    public void addCheckGroup(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.addCheckGroup(checkGroup);
        Integer checkGroupId = checkGroup.getId();
        addCheckGroup_checkitem(checkitemIds, checkGroupId);
    }

    private void addCheckGroup_checkitem(Integer[] checkitemIds, Integer checkGroupId) {
        if (checkitemIds != null&&checkitemIds.length>0) {
            for (Integer checkitemId : checkitemIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("checkgroup_id", checkGroupId);
                map.put("checkitem_id", checkitemId);
                checkGroupDao.addCheckGroup_checkitem(map);
            }
        }
    }

    @Override
    public PageInfo findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        List<CheckGroup> list = checkGroupDao.findPage(queryString);
        PageInfo<CheckGroup> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkGroupDao.findById(id);
    }

    @Override
    public List findCheckItem(Integer id) {
        return checkGroupDao.findCheckItem(id);
    }

    @Override
    public void update(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.update(checkGroup);
        Integer checkGroupId = checkGroup.getId();
        checkGroupDao.deleteCheckItemByGroupId(checkGroupId);
        addCheckGroup_checkitem(checkitemIds, checkGroupId);
    }

    @Override
    public void deleteById(Integer id) {
        long count = checkGroupDao.checkIsItem(id);
        System.out.println(id);
        if (count>0){
            throw new RuntimeException();
        }else {
            checkGroupDao.deleteCheckGroup(id);
        }
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }
}
